package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    private ApUserMapper apUserMapper;

    //app用户登录
    @Override
    public ResponseResult login(LoginDTO dto) {
        //非空判断
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否有手机号
        String phone = dto.getPhone();
        if (phone != null && dto.getPassword() != null) {
            //有手机号,使用手机号和密码登录,根据手机号查询数据库,获得账户信息
            LambdaQueryWrapper<ApUser> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(ApUser::getPhone, phone);
            ApUser apUser = apUserMapper.selectOne(wrapper);
            //非空判断
            if (apUser == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "该手机号未注册!");
            }
            //获取盐值,使用MD5混合加密计算
            String dbpassword = apUser.getPassword();
            String md5Password = MD5Utils.encode(dto.getPassword() + apUser.getSalt());
//            String md5Password = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
            //进行密码校验
            if (!md5Password.equals(apUser.getPassword())) {
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //验证通过,生成token
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            //创建Map集合,保存token和用户信息
            HashMap<String, Object> map = new HashMap<>();
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("token", token);
            map.put("user", apUser);
            //响应给调用者
            return ResponseResult.okResult(map);
        }
        //未登录,使用设备号生成jwt令牌
        if (dto.getEquipmentId() == null) {
            //未使用设备登录,提示错误
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        HashMap<String, Object> map = new HashMap<>();
        String token = AppJwtUtil.getToken(0L);
        map.put("token", token);
        return ResponseResult.okResult(map);
    }
}
